package com.codefish.codefishseckill.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.codefish.codefishseckill.entity.AuthUser;
import com.codefish.codefishseckill.entity.SecKillGoodsPermissionDO;
import com.codefish.codefishseckill.mapper.SecKillGoodsPermissionMapper;
import com.codefish.codefishseckill.service.SecKillGoodsPermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 秒杀商品权限表 服务实现类
 * </p>
 *
 * @author <a href='https://gitee.com/hzf2281'>codefish</a>
 * @since 2022-08-31
 */
@Service("ps")
@Slf4j
public class SecKillGoodsPermissionServiceImpl extends ServiceImpl<SecKillGoodsPermissionMapper, SecKillGoodsPermissionDO> implements SecKillGoodsPermissionService {
    @Autowired
    SecKillGoodsPermissionMapper secKillGoodsPermissionMapper;

    @Override
    public List<String> getPermissionsByGoodsId(Long goodsId) {
        return secKillGoodsPermissionMapper.getPermissionsByGoodsId(goodsId);
    }

    @Override
    public boolean hasPermission(Long goodsId) {
        //获取用户的认证信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        AuthUser authUser = (AuthUser) authentication.getPrincipal();
        //获取用户拥有的权限
        SimpleGrantedAuthority permissions = authUser.getPermissions().get(0);
        //获取秒杀商品需要的权限列表
        List<String> permissionList = this.getPermissionsByGoodsId(goodsId);
        boolean res = permissionList.contains(permissions.getAuthority());

        if (res) {
            log.info("用户拥有秒杀[{}]的权限[{}]", goodsId, permissions.getAuthority());
        } else {
            log.info("用户没有秒杀[{}]的权限，需要权限{},用户的权限为[{}]", goodsId, permissionList, permissions.getAuthority());
        }

        return res;
    }
}
